package dk.iha;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class SensorLoggerDatabase {
	
	/*DB columns*/
	public static final String KEY_ID = "Id";
	public static final String KEY_UNIQUE_ID_COLUMN = "UniqueId";
	public static final String KEY_LOGTIME_COLUMN = "LogTime";
	public static final String KEY_MOVEMENT_COLUMN = "Movement";
	public static final String KEY_LATITUDE_COLUMN = "Latitude";
	public static final String KEY_LONGITUDE_COLUMN = "Longitude";
	public static final String KEY_BATTERY_COLUMN = "Battery";
	public static final String KEY_TEMPERATURE_COLUMN = "Temperature";
	
	private DatabaseHelper databaseHelper;
	
	public SensorLoggerDatabase(Context context){ 
		databaseHelper = new DatabaseHelper(context, DatabaseHelper.DATABASE_NAME, null, DatabaseHelper.DATABASE_VERSION);
	}
	
	
	// Called when you no longer need access to the database.
	public void closeDatabase() {
		databaseHelper.close();
	}
	
	public long addNewLogEntry(LogItem log){
		// Create a new row of values to insert.
	    ContentValues newValues = new ContentValues();
	  
	    // Assign values for each row.
	    newValues.put(KEY_UNIQUE_ID_COLUMN, 	log.getUniqueId());
	    newValues.put(KEY_LOGTIME_COLUMN,   	log.getLogTime());
	    newValues.put(KEY_MOVEMENT_COLUMN,  	log.getMovement());
	    newValues.put(KEY_LATITUDE_COLUMN,  	log.getLatitude());
	    newValues.put(KEY_LONGITUDE_COLUMN, 	log.getLongitude());
	    newValues.put(KEY_BATTERY_COLUMN,   	log.getBatteryLevel());
	    newValues.put(KEY_TEMPERATURE_COLUMN,   log.gettemperature());
		
//		Log.w("WL", "addNewLogEntry:"+log.toString());

		// Insert the row into your table
	    SQLiteDatabase db = databaseHelper.getWritableDatabase();
	    return db.insert(DatabaseHelper.DATABASE_TABLE, null, newValues); 
	}

	public List<LogItem> getLogItemsbyUniquename(String Name){
		return getLogItems_general(KEY_UNIQUE_ID_COLUMN+"='"+Name+"'");
	}
	
	public List<LogItem> getLogItems(){
		return getLogItems_general(null);
	}

	private List<LogItem> getLogItems_general(String nameStatement){
		
		List<LogItem> items = new ArrayList<LogItem>();
		// Specify the result column projection. Return the minimum set
	    // of columns required to satisfy your requirements.
	    String[] result_columns = new String[] { 
	      "*", 
	      KEY_ID, 
	      KEY_UNIQUE_ID_COLUMN, 
	      KEY_LOGTIME_COLUMN, 
	      KEY_MOVEMENT_COLUMN,
	      KEY_LATITUDE_COLUMN,
	      KEY_LONGITUDE_COLUMN, 
	      KEY_BATTERY_COLUMN,
	      KEY_TEMPERATURE_COLUMN}; 
	    	 
	    // Replace these with valid SQL statements as necessary.
	    String where = nameStatement;
	    String whereArgs[] = null;
	    String groupBy = null;
	    String having = null;
	    String order = "Id DESC";
	    
	    SQLiteDatabase db = databaseHelper.getWritableDatabase();
	    Cursor cursor = db.query(DatabaseHelper.DATABASE_TABLE, result_columns, where, whereArgs, groupBy, having, order);
	    
	    // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                LogItem item = new LogItem();
                //cursor.getString(0) == db id
                item.setUniqueId(cursor.getString(1));
                item.setMovement(cursor.getString(2));
                item.setLogTime(cursor.getString(3));
                item.setLatitude(cursor.getString(4));
                item.setLongitude(cursor.getString(5));
                item.setBatteryLevel(cursor.getString(6));
                item.settemperature(cursor.getString(7));
                items.add(item);
            } while (cursor.moveToNext());
        }        
        return items;
	}
	
	public int deleteLogItemsWithUniqueId(String uniqueid){
		int numberOfRowsAffected = 0;
		String where = KEY_UNIQUE_ID_COLUMN+"='"+ uniqueid +"'";
	    String whereArgs[] = null;
		SQLiteDatabase db = databaseHelper.getWritableDatabase();
        numberOfRowsAffected = db.delete(DatabaseHelper.DATABASE_TABLE, where,whereArgs);
        db.close();
        return numberOfRowsAffected;
	}
	
	
	
	
	
	/*Helper class*/
	private static class DatabaseHelper extends SQLiteOpenHelper{
		private static final String DATABASE_NAME = "SensorLogger.db"; 
		private static final String DATABASE_TABLE = "SensorLog"; 
		private static final int DATABASE_VERSION = 1;
		
		
		
		// SQL Statement to create a new database.
		private static final String DATABASE_CREATE = "create table " +
		DATABASE_TABLE + " (" + KEY_ID +
		" integer primary key autoincrement, " + 
		KEY_UNIQUE_ID_COLUMN + " text not null, " +
		KEY_MOVEMENT_COLUMN + " text not null, " + 
		KEY_LOGTIME_COLUMN + " text not null, " + 
		KEY_LATITUDE_COLUMN + " text not null, " + 
		KEY_LONGITUDE_COLUMN +" text not null, " + 
		KEY_BATTERY_COLUMN +" text not null, " + 
		KEY_TEMPERATURE_COLUMN +" text not null " + 
		");";
		
		
		public DatabaseHelper(Context context, String name, 
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			
		}

		
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// Log the version upgrade.
			Log.w("SensorloggerDB", "Upgrading from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
			
			// Upgrade the existing database to conform to the new 
			// version. Multiple previous versions can be handled by 
			// comparing oldVersion and newVersion values.
			
			
			// The simplest case is to drop the old table and create a new one. 
			db.execSQL("DROP TABLE IF IT EXISTS " + DATABASE_TABLE);
			// Create a new one.
			onCreate(db);
			
		}
	}

}
